<?php

/**
 * Framework_Owner
 *
 * @author      Ian Szewczyk <roamzero@gmail.com>
 * @copyright   (c) 2007 Ian Szewczyk. All rights reserved.
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @package Framework
 * @filesource
 */


/**
 * Framework_Owner
 *
 * @package Framework
 */
class Framework_Owner 
{
	

	/**
     * $owner
     *
     * @access 		private
     * @static 
     * @var 		Framework_Owner 	$owner 		Singleton instance of owner object
     */
	private static $owner = null;

	/**
     * $isValid
     *
     * @access 		public
     * @var 		bool 		$isValid 		value on whether owner has been successfully selected
     */
	public $isValid = false;

	/**
     * $fileManager
     *
     * @access 		private
     * @var 		Framework_File 		$fileManager 		instance of File Manager
     */
	private $fileManager = null;
	
	/**
     * $ownerDB
     *
     * @access 		private
     * @var 		Framework_DB_Owner 		$ownerDB 		instance of Framework_DB_Common
     */
	public $ownerDB;

	
	/**
     * $ownerTable
     *
     * @access 		private
     * @var 		Framework_DB_Table_Owner		 $ownerTable 		instance of Framework_DB_Table_Common
     */
	public $ownerTable;
	
	/**
     * $siteUserTable
     *
     * @access 		private
     * @var 		Framework_DB_Table_Owner 		$siteUserTable 		instance of Framework_DB_Table_Common
     */
	public $siteUserTable;


	/**
     * __construct
     *
     * @author 		Ian Szewczyk <roamzero@gmail.com>
     * @access 		public
     * @param		string		$ownerName
     * @return 		void
     */
	public function __construct($ownerName)
	{
		
		$this->ownerDB = Framework_DB::dbFactory('Owner');
		
		$this->ownerTable = $this->ownerDB->getTable('Owner');
		
		
		
		$result = $this->ownerTable->load(array('loginName' => $ownerName));
		
		if (!PEAR::isError($result) && $this->ownerTable->isLoaded) {
			$this->siteUserTable = $this->ownerDB->getTable('SiteUser');
			
			$result = $this->siteUserTable->load(array('idOwner' => $this->idOwner));
			
			if (!PEAR::isError($result) && $this->siteUserTable->isLoaded) {
				$this->isValid = true;
			} else {
				$this->isValid = false;
			}
		} else {
			$this->isValid = false; 
		}
		
		
	
	}

	/**
     * getBasicData
     *
     * @access 		public 
     * @return 		array
     */
	public function getBasicData()
	{
		return array_merge($this->ownerTable->record, $this->siteUserTable->record);
	}

	/**
     * getFileManager
     *
     * @access 		public 
     * @return 		Framework_File		Instance of Framework_File
     */
	public function getFileManager()
	{
		if ($this->fileManager == null)
			$this->fileManager = new Framework_File($this);

		return $this->fileManager;
	}

	/**
     * friendStatus
     *
     * @access 		public 
     * @param 		Framework_User_Peopletab		Instance of Framework_User_Peopletab
     * @return 		integer
     */
	public function friendStatus($user)
	{
		
		$queryArray = array(
			'sqlKey' => 'getFriendStatus',
			'params' => array($this->idOwner, $user->idSiteUser)
		);
		
		$row = $this->ownerDB->select($queryArray);
		
		if(is_array($row)) {
			if($row['watchedByUser'] == 1 && $row['watchingUser'] == 1)
				return USER_FRIENDS_WITH_OWNER;
			elseif ($row['watchingUser'] == 1)
				return USER_WATCHED_BY_OWNER;
			elseif($row['watchedByUser'] == 1)
				return USER_WATCHING_OWNER; // Owner watched by user
		} else {
			return USER_NO_RELATION_OWNER; // Owner and User are unrelated
		}
	}
	

	
	/**
     * getProfileInfo
     *
     * @access 		public 
     * @param 		Framework_User_Peopletab		$user		Instance of Framework_User_Peopletab
     * @param 		string							$type	
     * @param 		Framework_Cache_Handler_Common	$cacheHandler	Instance of Framework_Cache_Handler_Common
     * @return 		array
     */
	public function getProfileInfo($user, $type = 'personal', $cacheHandler = null)
	{
		switch (true) {
			case $type == 'personal':
				$sqlKey = 'getPersonalInfo' ;
				$table = array('PersonalInfo');
				$params = array($this->idOwner);
			break;
			
			case $type == 'contact':
				$sqlKey = 'getContactInfo' ;
				$table = array('ContactInfo');
				$params = array($this->idOwner);
			break;
			
			case $type == 'interests':
				$sqlKey = 'getInterestsInfo' ;
				$table = array('InterestsInfo');
				$params = array($this->idOwner);
			break;
			
			default:
				$sqlKey = 'getAllInfo';	
				$table = array('PersonalInfo', 'InterestsInfo', 'ContactInfo');
				$params = array($this->idOwner, $this->idOwner, $this->idOwner);
			break;
		}
		
		$cols = array();
		
		foreach ($table as $item) {
			$tbl = $this->getTable($item);
			$cols = array_merge($cols, $tbl->getCol());
		}
		
		if($user->userStatus == NORMAL_USER_STATUS){
				if($user->friendStatus == USER_FRIENDS_WITH_OWNER)
					$filter = $table[0].'.privacy IN(2,3)';
				else
				$filter = $table[0].'.privacy IN(3)';
		} else if ($user->userStatus == OWNER_USER_STATUS) {
			$filter = $table[0].'.privacy IN(1,2,3)';
		} else {
			$filter = $table[0].'.privacy IN(3)';
		}
	
		$filter = $table[0].'.privacy IN(3)';
		$queryArray = array(
			'sqlKey' => $sqlKey,
			'params' => $params,
			'filter' => $filter
		);
		
		$result = $this->select($queryArray, $cacheHandler);
		
		
		
		$finalResult = array();
		
		if (count($result)) {
			foreach($result AS $item) {
				if(is_array($item)) {
					foreach($item AS $key => $val) {
						if($val != null && $key != 'idOwner' && $key != 'privacy') {
							if ($cols[$key]['qf_vals']) {
								if ($val != 'u') {
									$finalResult[$key]['value'] = $cols[$key]['qf_vals'][$val];
									$finalResult[$key]['label'] = $cols[$key]['qf_label'];
								}
							} else {
								$finalResult[$key]['value'] = $val;
								$finalResult[$key]['label'] = $cols[$key]['qf_label'];
							}
							
						}
					}
				}
			}
			
		}
		
		
		return $finalResult;
		
		
	}
	

	/**
     * birthday
     *
     * @access 		private
     * @param 		string		$birthday		Birth date in formay YYYY-MM-DD
     * @return 		mixed
     */
	private function birthday($birthday)
	{
		if(preg_match('/^\d{1,2}-\d{1,2}-\d{4}$/',$birthday)) {
			list($month,$day,$year) = explode("-",$birthday);
			$year_diff  = date("Y") - $year;
			$month_diff = date("m") - $month;
			$day_diff   = date("d") - $day;
			if ($month_diff < 0) $year_diff--;
			elseif (($month_diff==0) && ($day_diff < 0)) $year_diff--;
			return $year_diff;
		} else {
			return 'unknown';
		}
	}



	/**
     * save
     *
     * @access 		public
     * @param 		string		$group		Cache group affected
     * @return 		mixed		void, PEAR::error
     */
	public function save($group = null)
	{
		if ($this->isValid) {
			$this->ownerTable->save($group);
			$this->siteUserTable->save($group);
		} else {
			return PEAR::raiseError('Invalid Owner');
		}
	}

	/**
     * getCustomCSS
     *
     * @access 		ublic
     * @return 		mixed		false, reletive path to custom css file
     */
	public function getCustomCSS()
	{
		if ($this->customCSS) {
			$queryArray = array(
				'sqlKey' => 'getCustomCSS',
				'params' => $this->customCSS
			); 
			$result = $this->ownerDB->select($queryArray);
			if (is_array($result)) {
				return $result['filePointer'].'/'.$this->userName.'CSS.css';
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	/**
     * getCustomHeader
     *
     * @access 		public
     * @return 		mixed		false, reletive path to custom header file
     */
	public function getCustomHeader()
	{
		if ($this->customHeader) {
			$queryArray = array(
				'sqlKey' => 'getCustomHeader',
				'params' => $this->customHeader
			); 
			$result = $this->ownerDB->select($queryArray);
			if (is_array($result)) {
				return $result['filePointer'].'/'.$this->userName.'Header.'.$result['ext'];
			} else
			return false;
		} else {
			return false;
		}
	}

	/**
     * getPeople
     *
     * @access 		public
     * @param		string								$which
     * @param		integer								$pageSize
     * @param		string								$prefix
     * @param		Framework_Cache_Handler_Common		$cacheHandler
     * @return 		Framework_DB_Datagrid		
     */
	public function getPeople($which = 'friends', $pageSize = 10, $prefix='page', $cacheHandler = null)
	{
		switch (true) {
			case (strcasecmp($which,'friends') == 0 ):
				$watchStatus = array(1,1);
				break;

			case (strcasecmp($which,'watchedBy') == 0 ):
				$watchStatus = array(1,0);
				break;

			case (strcasecmp($which,'watching') == 0 ):
				$watchStatus = array(0,1);
				break;

			default:
				$watchStatus = array(1,1); // friends
				break;
		}
		
		$queryArray = array(
			'sqlKey' => 'getPeople',
			'params' => array($this->idOwner, $watchStatus[0], $watchStatus[1]),
		);

		return Framework_DB::dataGridFactory($this->ownerDB, $queryArray, $pageSize, $prefix, $cacheHandler);
	}
	
	

	/**
     * updateVisitHistory
     *
     * @access 		public
     * @param		integer			$idSiteUser
     * @return 		Void	
     */
	public function updateVisitHistory($idSiteUser)
	{
		$visitHistoryTable = Framework_DB::tableFactory('VisitHistory');
		
		$visitHistoryTable->load(array('idOwner'=>$this->idOwner, 'idSiteUser' => $idSiteUser));
		
		$visitHistoryTable->idOwner = $this->idOwner;
		
		$visitHistoryTable->idSiteUser = $idSiteUser;
		
		$visitHistoryTable->dateVisited = time();
		
		$visitHistoryTable->save();
		
		$old = time() - (3*24*60*60);
		
		$visitHistoryTable->delete('dateVisited < '.$old);
	}
	
	/**
     * getVisitHistory
     *
     * @access 		public
     * @return 		mixed		Array, PEAR::error	
     */
	public function getVisitHistory()
	{
		
		$queryArray = array(
			'sqlKey' => array(
				'select' => 'userName, siteDomain, dateVisited',
				'from'   => 'SiteUser, VisitHistory',
				'where'  => 'SiteUser.idSiteUser = VisitHistory.idSiteUser
							AND VisitHistory.idOwner = ?',
				'order'  => 'VisitHistory.dateVisited ASC LIMIT 15'
			),
			'params' => array($this->idOwner)
		);
		
		return $this->select($queryArray);
	
		
	}
	
	/**
     * getCurrentlyBrowsing
     *
     * @access 		public
	 * @return 		Mixed	array, PEAR::error
     */
	public function getCurrentlyBrowsing(){
		// Currently Browsing
		$time = time() - 120;
		
		$queryArray = array(
			'sqlKey' => array(
				'select' => 'userName, siteDomain',
				'from'   => 'SiteUser, Session',
				'where'  => 'SiteUser.idSiteUser = Session.idSiteUser
							AND Session.curBrowse = ?
							AND Session.dateTouched > ?'
			),
			'params' => array($this->idSiteUser, $time)
		);
		return $this->select($queryArray);
	}

	
	/**
     * getSites
     *
     * @access 		public
     * @param		Framework_Cache_Handler_Common		$cacheHandler
	 * @return 		Mixed	array, PEAR::error
     */
	public function getSites($cacheHandler = null){
		$queryArray = array(
			'sqlKey' => 'getSites',
			'params' => array($this->idSiteUser)
 		);
		
		return $this->ownerDB->select($queryArray, $cacheHandler);
	}


	/**
     * singleton
     *
     * @access public
     * @return mixed PEAR_Error on failure, user class on success
     * @static
     */
	static public function singleton($cacheHandler = null, $ownerName = null)
	{
		if (is_null(self::$owner)) {
			self::$owner = new Framework_Owner(($ownerName ? $ownerName : Framework::$request->ownerName));
		}
		
		if (!is_null($cacheHandler)) {
			Framework_DB::logDependency($cacheHandler, 'SiteUser');
			Framework_DB::logDependency($cacheHandler, 'Owner');
		}

		return self::$owner;
	}
	
	/**
     * __get
     *
     * @access public
     * @param string $var Name of var 
     * @return mixed Null if the var does not exist, var's value if it does 
     */
	public function __get($var)
	{
		if ($this->ownerTable->$var) {
			return $this->ownerTable->$var;
		} else if ($this->siteUserTable->$var) {
			return $this->siteUserTable->$var;
		}

		return null;
	}

	/**
     * __set
     *
     * @access public
     * @param string $var Name of var to set
     * @param mixed $val Value of given var
     * @return void
     * @see Framework_User::$data
     */
	public function __set($var,$val)
	{
		if(in_array($var,$this->ownerTable->columns)) {
			$this->ownerTable->$var = $val;
			return;
		}
		
		if(in_array($var,$this->siteUserTable->columns)) {
			$this->siteUserTable->$var = $val;
		}
			
	}
	
	/**
     * __call
     *
     * @access 		public
     * @return 		mixed	
     */
	public function __call($function, $args)
	{
		return call_user_func_array(array(&$this->ownerDB,$function),$args);
	}


}

?>